package com.yswy.backstage.serviceApi.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yswy.backstage.dto.api.UserDeviceInfo;
import com.yswy.backstage.service.TgDeductionService;
import com.yswy.backstage.serviceApi.ApiTgChannelService;
import com.yswy.common.utils.DateUtils;
import com.yswy.common.utils.StringUtils;
import com.yswy.common.utils.TgKlUtil;
import com.yswy.common.utils.UserLockUtils;
import com.yswy.common.utils.redis.RedisConstants;
import com.yswy.common.utils.redis.RedisUtil;
import com.yswy.domain.common.BasePojo;
import com.yswy.domain.entity.tf.TgChannel;
import com.yswy.domain.entity.tf.TgDeduction;
import com.yswy.domain.entity.tf.TgDeductionChild;
import com.yswy.domain.entity.tf.TgEventEnums;
import com.yswy.domain.mapper.tf.TgChannelMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Slf4j
@Service
public class ApiTgChannelServiceImpl extends ServiceImpl<TgChannelMapper, TgChannel>
        implements ApiTgChannelService {
    @Autowired
    private  TgDeductionService tgDeductionService;

    static Map<String ,List<Integer>> integersTgChannle = new HashMap();
    static String spileCode = "-";
    @Override
    public Boolean isDeduction(String channle , Integer price) {
        synchronized (UserLockUtils.getLock("channleDeduction:"+channle)){
            //获取扣量缓存
            Integer deduction =  getIntegers(channle);
            if (deduction== null){
                TgChannel tgChannle = getOne(new LambdaQueryWrapper<TgChannel>()
                        .like(TgChannel::getChannel ,channle)
                        .eq(BasePojo::getIsDel , 0));
                if (tgChannle==null){
                    return false ;
                }else {
                    if (price !=null){
                        if (tgChannle.getExaminePrice() > price){
                            log.info("渠道："+channle+"，考核价格不大于付费价格 不回传,考核价格："+tgChannle.getExaminePrice()+" 付款价格："+price);
                            return false ;
                        }
                    }
                    List<TgDeduction> tgDeductions =  tgDeductionService.listTgDeduction(tgChannle.getTgDeductionId());
                    if (tgDeductions.size()<=0){
                        log.info("渠道："+channle+"，未配置扣量参数，配置错误不回传");
                        return false ;
                    }
                    TgDeduction tgDeduction = tgDeductions.get(0);
                    for (TgDeductionChild t:
                            tgDeduction.getTgDeductionChildrens()) {
                        if (DateUtils.belongCalendar(t.getStartTime() , t.getEndTime(),
                                "HH:mm:ss")){
                            String channlenew = tgChannle.getChannel()+spileCode+t.getStartTime()+spileCode+t.getEndTime();
                            deduction = getIntegers( channlenew , t.getProportion());
                            break;
                        }
                    }
                }
            }
            if (deduction == null){
                log.info("渠道："+channle+"，没有配置扣量参数");
                return true ;
            }else {
                if (deduction ==0){
                    log.info("渠道："+channle+"，返回扣量");
                    return true ;
                }else {
                    log.info("渠道："+channle+"，返回不扣量");
                    return false ;
                }
            }
        }
    }


    @Override
    public void delDeductionByTgDeduction(Long tgDeductionId) {
        List<TgChannel> tgChannels = list(new LambdaQueryWrapper<TgChannel>().eq(TgChannel::getTgDeductionId , tgDeductionId));
        List<TgDeduction> tgDeductions =  tgDeductionService.listTgDeduction(tgDeductionId);
        if (tgDeductions.size()<=0){
            return ;
        }
        TgDeduction tgDeduction = tgDeductions.get(0);
        List<TgDeductionChild> tgDeductionChildrens = tgDeduction.getTgDeductionChildrens();
        if (tgDeductionChildrens.size()<=0){
            return;
        }

        for (TgChannel tgChannel : tgChannels){
            for (TgDeductionChild t:tgDeductionChildrens) {
                delDeduction(tgChannel.getChannel() ,t.getStartTime() , t.getEndTime());
            }
        }

    }

    @Override
    public void delDeductionByTgChannel(Long tgChannelId) {
        TgChannel tgChannel = getById(tgChannelId);
        List<TgDeduction> tgDeductions =  tgDeductionService.listTgDeduction(tgChannel.getTgDeductionId());
        if (tgDeductions.size()<=0){
            return ;
        }
        TgDeduction tgDeduction = tgDeductions.get(0);
        List<TgDeductionChild> tgDeductionChildrens = tgDeduction.getTgDeductionChildrens();
        if (tgDeductionChildrens.size()<=0){
            return;
        }
        for (TgDeductionChild t:tgDeductionChildrens) {
            delDeduction(tgChannel.getChannel() ,t.getStartTime() , t.getEndTime());
        }

    }

    public void delDeduction(String channle , String star , String stop) {
        log.info("清楚扣量："+channle+spileCode+star+spileCode+stop);
        List<Integer> integers = integersTgChannle.get(channle);
        if (integers != null){
            log.info("清楚扣量："+channle+spileCode+star+spileCode+stop +"剩余数量："+integers.size());
        }
        integersTgChannle.remove(channle);
    }



    public static void main(String[] args) {
        System.out.println(DateUtils.belongCalendar( "2023-06-24 13:08:07", "2023-06-24 23:59:59",
                "yyyy-MM-dd HH:mm:ss"));
    }



    public static List<Integer> setIntegers(String channel , Integer proportion){
        List<Integer> list = TgKlUtil.getList(proportion);
        integersTgChannle.put(channel , list);
        return list ;
    }



    public static Integer getIntegers( String channel , Integer proportion){
        Integer i = null;
        List<Integer> list = integersTgChannle.get(channel);

        if (list == null || list.size() <= 0){
            list = setIntegers(channel , proportion);
        }
        i = list.get(0);
        list.remove(0);
        integersTgChannle.put(channel ,list );
        log.info("渠道："+channel+"缓存扣量剩余: "+list.size());
        return i ;
    }


    public static Integer getIntegers(String channel){
        //在匹配父级扣量配置
        for (String key : integersTgChannle.keySet()) {
            String[] strings = key.split("-");
            String mapChannle = strings[0];
            if (channel.equals(mapChannle)){
                List<Integer> value = integersTgChannle.get(key);
                Integer i = value.get(0);
                value.remove(0);
                integersTgChannle.put(channel ,value );
                return i ;
            }
        }
        return null;
    }


}

